import Vue from 'vue';
import axios from 'axios';

axios.defaults.baseURL = (() => {
  if (process.env.NODE_ENV === 'development') {
    return 'http://localhost:3000';
  }
  return 'http://api.crqcn.com';
})();
axios.defaults.transformRequest = [
  data => {
    let ret = '';
    if (data) {
      Object.keys(data).forEach(it => {
        ret += `${encodeURIComponent(it)}=${encodeURIComponent(data[it])}&`;
      });
    }
    return ret;
  },
];

// http请求拦截器
axios.interceptors.request.use(
  config => {
    /* eslint-disable no-param-reassign */
    config.headers = config.headers || {};
    if (Vue.prototype.$common.GetSysTokenSession('accessToken')) {
      config.headers['Access-Token'] = Vue.prototype.$common.GetSysTokenSession('accessToken');
      config.headers['Permit-Token'] = Vue.prototype.$common.GetSysTokenSession('permitToken');
    }
    return config;
  },
  err => Promise.reject(err)
);

// http响应拦截器
axios.interceptors.response.use(
  response => {
    if ('access-token' in response.headers) {
      setTimeout(() => {
        Vue.prototype.$common.SetSysTokenSession('accessToken', response.headers['access-token']);
      }, 0);
    }
    if ('permit-token' in response.headers) {
      setTimeout(() => {
        Vue.prototype.$common.SetSysTokenSession('permitToken', response.headers['permit-token']);
      }, 0);
    }
    if (typeof response.data === 'object') {
      if ('flag' in response.data) {
        if ('code' in response.data) {
          response.data.code = Number.parseInt(response.data.code, 10);
          if (response.data.flag === 'False') {
            if (response.data.code === 0) {
              // 警告
              if (response.data.message) {
                Vue.prototype.$notify.warning({
                  message: response.data.message,
                });
              }
            } else if (response.data.code === 1 && !/menutree/gi.test(response.config.url)) {
              // 登录超时
              Vue.prototype.$notify.warning({ message: '登录超时,请重新登录' });
              setTimeout(() => {
                localStorage.clear();
                window.location.replace('/');
              }, 500);
            } else if (response.data.code === 2) {
              window.location.href = '/error';
            } else {
              // todo
            }
          }
        }
      }
    }
    return response;
  },
  err => {
    if (err.response) {
      Vue.prototype.$message.error(err.response.data.message);
    }
    return Promise.reject(err);
  }
);

Vue.prototype.$http = axios;
Vue.prototype.$defaultBaseUrl = axios.defaults.baseURL;
